<template>
  <div class="square-container">
    <div class="main-content">
      <!-- 顶部筛选栏 -->
      <div class="filter-bar">
        <div class="filter-group">
          <Button 
            v-for="(filter, index) in filters" 
            :key="index"
            :type="currentFilter === index ? 'primary' : 'default'"
            @click="changeFilter(index)">
            {{ filter.name }}
          </Button>
        </div>
        
        <div class="sort-group">
          <Select v-model="sortType" style="width:120px">
            <Option v-for="(sort, index) in sortOptions" 
                    :key="index" 
                    :value="sort.value">
              {{ sort.label }}
            </Option>
          </Select>
        </div>
      </div>

      <!-- 帖子列表 -->
      <div class="posts-container">
        <SXQFriendUpdateList 
          :friend-list="postsList" 
          :callback="loadPosts"
        />
        
        <!-- 分页器 -->
        <div class="pagination">
          <Page 
            :total="total" 
            :page-size="pageSize"
            :current="currentPage"
            show-total
            @on-change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <!-- 右侧信息栏 -->
    <div class="sidebar">
      <!-- 热门话题 -->
      <Card class="sidebar-card">
        <p slot="title">
          <Icon type="ios-flame" />
          热门话题
        </p>
        <ul class="hot-topics">
          <li v-for="(topic, index) in hotTopics" :key="index">
            <span class="topic-rank" :class="{'top-rank': index < 3}">{{ index + 1 }}</span>
            <span class="topic-title"># {{ topic.title }}</span>
            <span class="topic-count">{{ topic.count }}</span>
          </li>
        </ul>
      </Card>

      <!-- 活跃用户 -->
      <Card class="sidebar-card">
        <p slot="title">
          <Icon type="ios-people" />
          活跃用户
        </p>
        <div class="active-users">
          <div v-for="(user, index) in activeUsers" 
               :key="index" 
               class="user-item"
               @click="goUser(user.id)">
            <Avatar :src="user.avatar" />
            <span class="user-name">{{ user.nickname }}</span>
            <span class="post-count">{{ user.friendUpdateCount }}帖</span>
          </div>
        </div>
      </Card>
    </div>
  </div>
</template>

<script>
import {friendUpdatesPageQuery, friendUpdatesCount, getActiveUser} from "@/api/api";
import SXQFriendUpdateList from "@/components/SXQ-FriendUpdateList";

export default {
  name: "SquarePage",
  components: { SXQFriendUpdateList },
  
  data() {
    return {
      filters: [
        { name: '全部' },
        { name: '最新' },
        { name: '热门' }
      ],
      currentFilter: 0,
      
      sortOptions: [
        { label: '最新发布', value: 'time' },
        { label: '最多点赞', value: 'like' },
        { label: '最多评论', value: 'comment' }
      ],
      sortType: 'time',
      
      postsList: [],
      total: 0,
      pageSize: 5,
      currentPage: 1,

      hotTopics: [
        { title: '技术分享', count: '1.2k讨论' },
        { title: '生活日常', count: '998讨论' },
        { title: '职场经验', count: '876讨论' },
        { title: '美食推荐', count: '654讨论' },
        { title: '旅行记录', count: '432讨论' }
      ],

      activeUsers: []
    };
  },

  watch: {
    /**
     * 监听排序方式变化
     * 当排序方式改变时重新加载帖子列表
     */
    sortType() {
      this.loadPosts();
    }
  },

  /**
   * 组件创建时获取活跃用户列表
   */
  created() {
    getActiveUser().then(res => {
      if (res.body.code === 1) {
        this.activeUsers = res.body.data;
      }
    });
  },

  /**
   * 组件挂载时初始化数据
   * 加载帖子列表和总数
   */
  mounted() {
    this.loadPosts();
    this.getTotal();
  },

  methods: {
    /**
     * 跳转到用户个人页面
     * @param {number} id - 用户ID
     */
    goUser(id) {
      this.$router.push({
        path: '/PersonalPage',
        query: { userId: id }
      });
    },

    /**
     * 切换筛选方式
     * @param {number} index - 筛选选项的索引
     * 0: 全部, 1: 最新, 2: 热门
     */
    changeFilter(index) {
      this.currentFilter = index;
      if (index === 1) {
        this.sortType = 'time';
      } else if (index === 2) {
        this.sortType = 'hot';
      }
      this.loadPosts();
    },

    /**
     * 处理分页变化
     * @param {number} page - 目标页码
     */
    handlePageChange(page) {
      this.currentPage = page;
      this.loadPosts();
    },

    /**
     * 获取帖子总数
     * 用于分页显示
     */
    getTotal() {
      friendUpdatesCount().then(res => {
        if (res.body.code === 1) {
          this.total = res.body.data;
        }
      });
    },

    /**
     * 加载帖子列表
     * 根据当前页码、筛选方式和排序方式获取数据
     * 支持多种排序方式：
     * - time: 按时间排序
     * - like: 按点赞数排序
     * - comment: 按评论数排序
     * - hot: 按综合热度排序
     */
    loadPosts() {
      friendUpdatesPageQuery(this.currentPage, this.pageSize).then(res => {
        if (res.body.code === 1) {
          const data = res.body.data;
          let list = data.map(it => ({
            id: it.id,
            img: it.img,
            nums: [it.hitsCount, it.likeCount, it.commentCount, it.collectCount, it.shareCount],
            content: it.content,
            title: it.title,
            createTime: it.createTime,
            avatar: it.avatar,
            nickname: it.nickname,
            userId: it.userId
          }));

          // 根据筛选方式和排序类型处理数据
          if (this.currentFilter !== 1) {
            switch(this.sortType) {
              case 'like':
                // 按点赞数降序排序
                list.sort((a, b) => b.nums[1] - a.nums[1]);
                break;
              case 'comment':
                // 按评论数降序排序
                list.sort((a, b) => b.nums[2] - a.nums[2]);
                break;
              case 'hot':
                // 按综合热度（浏览、点赞、评论、收藏数之和）降序排序
                list.sort((a, b) => {
                  const scoreA = a.nums[0] + a.nums[1] + a.nums[2] + a.nums[3];
                  const scoreB = b.nums[0] + b.nums[1] + b.nums[2] + b.nums[3];
                  return scoreB - scoreA;
                });
                break;
              default:
                // 默认按发布时间降序排序
                list.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
            }
          }

          this.postsList = list;
        } else {
          this.$Message.error(res.body.msg);
        }
      });
    }
  }
};
</script>

<style scoped>
.square-container {
  width: 75vw;
  margin: 20px auto;
  display: flex;
  gap: 20px;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.filter-bar {
  background: white;
  padding: 16px;
  border-radius: 10px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-group {
  display: flex;
  gap: 10px;
}

.posts-container {
  background: white;
  border-radius: 10px;
  padding: 20px;
  min-height: 400px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
  padding: 20px 0;
}

.sidebar {
  width: 300px;
  flex-shrink: 0;
}

.sidebar-card {
  margin-bottom: 20px;
  border-radius: 10px;
}

.hot-topics {
  list-style: none;
  padding: 0;
  margin: 0;
}

.hot-topics li {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.hot-topics li:last-child {
  border-bottom: none;
}

.topic-rank {
  width: 24px;
  height: 24px;
  background: #f0f0f0;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  font-size: 12px;
}

.top-rank {
  background: #ff4d4f;
  color: white;
}

.topic-title {
  flex: 1;
  color: #666;
}

.topic-count {
  color: #999;
  font-size: 12px;
}

.active-users {
  display: flex;
  flex-direction: column;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.user-item:hover {
  background: #f0f0f0;
}

.user-name {
  margin-left: 10px;
  flex: 1;
  font-size: 14px;
}

.post-count {
  color: #999;
  font-size: 12px;
}
</style>